package com.cloud.jucTest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**注意这个注释
 * If a task can be successfully queued, then we
 * still need to double-check whether we should
 * have added a thread (because existing ones
 * died since last checking) or that the pool shut
 * down since entry into this method. So we recheck
 * state and if necessary roll back the enqueuing
 * if stopped, or start a new thread if there are none.
 */
public class ExcutorTest {
    private static class Task implements Runnable {
        Integer i;
        Long start;
        public Task(Integer i, Long start) {
            this.i = i;
            this.start = start;
        }

        @Override
        public void run() {
            System.out.println("task" + i + "is running");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Long end = System.currentTimeMillis();
            Thread.currentThread().setName("Thread" + i);
            System.out.println("the task " + Thread.currentThread().getName() +" is finish use time " + (end - start));
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = new ThreadPoolExecutor(0, 3, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 4 ; ++i) {
            executorService.execute(new Task(i, start));
        }
        Thread.sleep(2000);
        executorService.shutdown();
        System.out.println("over");
    }
}
